package se.thoka.twt.server;

import javax.servlet.http.HttpServletRequest;

import se.thoka.twt.client.users.AbstractUser;
import se.thoka.twt.server.item.AbstractUserDatastore;
import se.thoka.twt.shared.exceptions.NoSuchObjectException;
import se.thoka.twt.shared.exceptions.SessionTimeoutException;
import se.thoka.twt.shared.exceptions.UserLoginFailedException;

public abstract class SessionHandler<U extends AbstractUser, DS extends AbstractUserDatastore<U>> {

	private static final String ATTR_USERID = "user";
	
	protected SessionHandler() {}
	
	public String getUserId(HttpServletRequest request) throws SessionTimeoutException {
		String result = (String) request.getSession().getAttribute(ATTR_USERID);
		if (result == null) {
			throw new SessionTimeoutException();
		}
		
		return result;
	}
	
	public U getUser(HttpServletRequest request) throws SessionTimeoutException {
		String userid = getUserId(request);
		
		try {
			return getUserDatastore().selectById(userid);
		} catch (Exception e) {
			e.printStackTrace();
			throw new SessionTimeoutException();
		}
	}
	
	public U loginUser(HttpServletRequest request, String username, String password) throws UserLoginFailedException {
		U result;
		
		logoutUser(request);
		
		try {
			result = getUserDatastore().getUserWithPassword(username, password);
			request.getSession().setAttribute(ATTR_USERID, result.getId());
		} catch (NoSuchObjectException e) {
			throw new UserLoginFailedException();
		}
		
		return result;
	}
	
	public void logoutUser(HttpServletRequest request) {
		request.getSession().invalidate();
	}
	
	protected abstract DS getUserDatastore();
}
